package ru.sstu.renju.javafx.renderers;

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

import ru.sstu.renju.core.Row;

/**
 * {@link BlackWhiteRenderer} class is used for rendering black and white
 * stones.
 *
 * @author denis_murashev
 * @since Renju 1.1
 */
public class BlackWhiteRenderer extends FXRenderer {

	private static final float COEF = 0.7f;

	/**
	 * Black and White Renderer initialization.
	 */
	public BlackWhiteRenderer() {
		super("Classic Black and White");
	}

	@Override
	public void paintField(GraphicsContext g) {
		int cell = getCellSize();
		int size = getGameSize() * cell;
		int half = cell / 2;
		g.setFill(Color.ORANGE);
		g.fillRect(0, 0, size, size);
		g.setStroke(Color.BLACK);
		for (int i = 0; i < getGameSize(); i++) {
			g.strokeLine(i * cell + half, half, i * cell + half, size - half);
//			g.drawLine(i * cell + half, half, i * cell + half, size - half);
		}
		for (int i = 0; i < getGameSize(); i++) {
			g.strokeLine(half, i * cell + half, size - half, i * cell + half);
//			g.drawLine(half, i * cell + half, size - half, i * cell + half);
		}
	}

	@Override
	public void paintRow(GraphicsContext g, Row row) {
		if (row != null) {
			int cell = getCellSize();
			int dx = row.getDirection().getDx();
			int dy = row.getDirection().getDy();
			int x1 = row.getX() * cell + cell / 2;
			int y1 = row.getY() * cell + cell / 2;
			int x2 = x1 + cell * (getRowSize() - 1) * dx;
			int y2 = y1 + cell * (getRowSize() - 1) * dy;
			g.setFill(Color.RED);
			final int width = 4;
			double[] x = {
					x1 + width * (dy - dx),
					x2 + width * (dy + dx),
					x2 - width * (dy - dx),
					x1 - width * (dy + dx),
			};
			double[] y = {
					y1 - width * (dx + dy),
					y2 - width * (dx - dy),
					y2 + width * (dx + dy),
					y1 + width * (dx - dy),
			};
			g.fillPolygon(x, y, x.length);
		}
	}

	@Override
	protected void paintBlack(GraphicsContext g, int i, int j) {
		paintCell(g, i, j, Color.BLACK);
	}

	@Override
	protected void paintWhite(GraphicsContext g, int i, int j) {
		paintCell(g, i, j, Color.WHITE);
	}

	private void paintCell(GraphicsContext g, int i, int j, Color color) {
		int cell = getCellSize();
		int x = i * cell + (int) ((1 - COEF) * cell / 2);
		int y = j * cell + (int) ((1 - COEF) * cell / 2);
		int size = (int) (COEF * cell);
		g.setFill(color);
		g.fillOval(x, y, size, size);
	}
}
